﻿/*************************************************************************************

- CLR版本：        4.0.30319.42000
- 类 名 称：       ImageConvert
- 机器名称：       YTE
- 命名空间：       LD.Vision
- 文 件 名：       ImageConvert
- 创建时间：       2022/7/15 9:41:27
- 作    者：       YTE
- 说   明：
- 修改时间：
- 修 改 人：
  *************************************************************************************/

using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LD.Vision
{
    public class ImageConvert
    {
        /// <summary>
        /// Bitmap转换成HImage
        /// </summary>
        /// <param name="bImage"></param>
        /// <returns></returns>
        public HImage BitmapToHImage(Bitmap bImage)
        {
            Bitmap bImage8;
            BitmapData bmData = null;
            Rectangle rect;
            IntPtr pBitmap;
            IntPtr pPixels;
            HImage hImage = new HImage();


            rect = new Rectangle(0, 0, bImage.Width, bImage.Height);
            bImage8 = new Bitmap(bImage.Width, bImage.Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bImage8);
            g.DrawImage(bImage, rect);
            g.Dispose();


            bmData = bImage8.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            pBitmap = bmData.Scan0;
            pPixels = pBitmap;


            hImage.GenImage1("byte", bImage.Width, bImage.Height, pPixels);


            bImage8.UnlockBits(bmData);


            return hImage;
        }
        /// <summary>
        /// 彩色图Bitmap转换成HImage
        /// </summary>
        /// <param name="bImage"></param>
        /// <returns></returns>
        public HImage BitmapToHImageByColor(Bitmap bImage)
        {
            Bitmap bImage24;
            BitmapData bmData = null;
            Rectangle rect;
            IntPtr pBitmap;
            IntPtr pPixels;
            HImage hImage = new HImage();


            rect = new Rectangle(0, 0, bImage.Width, bImage.Height);
            bImage24 = new Bitmap(bImage.Width, bImage.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bImage24);
            g.DrawImage(bImage, rect);
            g.Dispose();

            bmData = bImage24.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            pBitmap = bmData.Scan0;
            pPixels = pBitmap;

            hImage.GenImageInterleaved(pPixels, "bgr", bImage.Width, bImage.Height, -1, "byte", 0, 0, 0, 0, -1, 0);

            bImage24.UnlockBits(bmData);
            return hImage;
        }
    }
}
